import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_application_cyber/net/cn_net_helper.dart';
import 'package:flutter_application_cyber/model/cn_net_response.dart';
import 'package:flutter_application_cyber/pages/Home/cn_call_wait_page.dart';
import 'package:provider/provider.dart';
import 'package:flutter_application_cyber/pages/Mate/Models/cn_AnchorViewModel.dart';
import 'package:flutter_application_cyber/model/cn_anchor_model.dart';
import 'package:flutter_application_cyber/tools/cn_database_helper.dart';
import 'package:flutter_util_code/toast_utils.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../../tools/cn_event_bus.dart';
import 'dart:async';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';

class CnHomePage extends StatefulWidget {
  const CnHomePage({Key? key}) : super(key: key);

  @override
  State<CnHomePage> createState() => _CnHomePagePageState();
}

typedef FunctionTest<String> = void Function(int index);

class _CnHomePagePageState extends State<CnHomePage> {
  List<CnAnchorModel> anchorList = [];
  List homeImageList = [
    ['assets/homeImages/a_10001.jpg', 'assets/homeImages/a_10002.jpg'],
    ['assets/homeImages/b_10001.jpg', 'assets/homeImages/b_10002.jpg'],
    [
      'assets/homeImages/c_10001.jpg',
      'assets/homeImages/c_10002.jpg',
      'assets/homeImages/c_10003.jpg'
    ],
    ['assets/homeImages/d_10001.jpg', 'assets/homeImages/d_10002.jpg'],
    [
      'assets/homeImages/e_10001.jpg',
      'assets/homeImages/e_10002.jpg',
      'assets/homeImages/e_10003.jpg'
    ],
    ['assets/homeImages/f_10001.jpg', 'assets/homeImages/f_10002.jpg'],
    [
      'assets/homeImages/g_10001.jpg',
      'assets/homeImages/g_10002.jpg',
      'assets/homeImages/g_10003.jpg'
    ],
    [
      'assets/homeImages/h_10001.jpg',
      'assets/homeImages/h_10002.jpg',
      'assets/homeImages/h_10003.jpg'
    ],
    [
      'assets/homeImages/i_10001.jpg',
      'assets/homeImages/i_10002.jpg',
      'assets/homeImages/i_10003.jpg'
    ],
    [
      'assets/homeImages/j_10001.jpg',
      'assets/homeImages/j_10002.jpg',
      'assets/homeImages/j_10003.jpg'
    ],
    [
      'assets/homeImages/k_10001.jpg',
      'assets/homeImages/k_10002.jpg',
      'assets/homeImages/k_10003.jpg'
    ],
    ['assets/homeImages/l_10001.jpg', 'assets/homeImages/l_10002.jpg'],
  ];

  //是否在加载
  bool _isLoadMore = false;

  //当前页数
  int page = 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      width: double.infinity,
      decoration: BoxDecoration(
        image: DecorationImage(
            image: AssetImage('images/icon_page_bg_1.png'), fit: BoxFit.fill),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 100,
            height: 30,
            margin: EdgeInsets.only(left: 20, top: 60, bottom: 20),
            child: Image.asset('images/icon_home_discover.png'),
          ),
          Expanded(
              child: Stack(
            children: [
              Container(
                  constraints: BoxConstraints(maxHeight: 1000),
                  child: MediaQuery.removePadding(
                    context: context,
                    removeTop: true,
                    child: ListView.builder(
                        scrollDirection: Axis.vertical, // 滚动方向
                        itemCount: anchorList.length,
                        itemBuilder: (context, index) {
                          CnAnchorModel model = anchorList[index];
                          return InkWell(
                              onTap: () {
                                _showInfoDialog(context, model, (index) {
                                  Future.delayed(Duration(seconds: 1), () {
                                    if (index == 0) {
                                      //拨打电话
                                      Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                              builder: (context) =>
                                                  CnCallWaitPage(
                                                    nikeName: model.nickname,
                                                    avatarUrl: model.avatar,
                                                  )));
                                    } else {
                                      //聊天
                                      Map arg = {
                                        "coversationType":
                                            RCIMIWConversationType.private,
                                        "targetId": model.userId,
                                        'nickName': model.nickname
                                      };
                                      Navigator.pushNamed(
                                          context, "/conversation",
                                          arguments: arg);
                                    }
                                  });
                                });
                              },
                              child: Container(
                                decoration: const BoxDecoration(
                                  image: DecorationImage(
                                      image: AssetImage(
                                          'images/icon_home_item_bg.png'),
                                      fit: BoxFit.fill),
                                ),
                                height: 300,
                                margin: EdgeInsets.only(
                                    left: 16, right: 16, bottom: 10),
                                child: Column(
                                  children: [
                                    Container(
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.end,
                                        children: [
                                          InkWell(
                                            onTap: () {
                                              UserInfoModel? userData =
                                                  UserInfoModel();
                                              userData.userId = model.userId;
                                              userData.isFollow =
                                                  model.isFollow;
                                              //更多弹窗
                                              CnAnchorViewModel.getInfo()
                                                  .showMoreDialog(
                                                      context, userData,
                                                      (value) {
                                                CnEventBus.instance!.commit(
                                                    EventKeys
                                                        .FollowListPageMessage,
                                                    null);
                                                // 关注、取消关注
                                                if (value == 'follow') {
                                                  model.isFollow = true;
                                                } else if (value ==
                                                    'followed') {
                                                  model.isFollow = false;
                                                } else if (value == 'block') {
                                                  loadMore();
                                                }
                                              });
                                            },
                                            child: Container(
                                              margin: EdgeInsets.only(
                                                  right: 10, top: 5),
                                              width: 30,
                                              height: 30,
                                              child: Image.asset(
                                                  'images/icon_more_btn.png'),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    Container(
                                      margin: EdgeInsets.only(
                                          top: 30, left: 10, right: 10),
                                      height: 180,
                                      width: double.infinity,
                                      child: model.imageMapPaths.length > 0
                                          ? Image.asset(
                                              model.imageMapPaths[0],
                                              fit: BoxFit.cover,
                                            )
                                          : Image.asset(
                                              'assets/homeImages/a_10001.jpg',
                                              fit: BoxFit.cover,
                                            ),
                                    ),
                                    Container(
                                      margin: EdgeInsets.only(top: 10),
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Row(
                                            children: [
                                              SizedBox(
                                                width: 10,
                                              ),
                                              Container(
                                                width: 30,
                                                height: 30,
                                                clipBehavior: Clip.hardEdge,
                                                decoration: BoxDecoration(
                                                  borderRadius:
                                                      BorderRadius.circular(15),
                                                ),
                                                child:
                                                    Image.network(model.avatar),
                                              ),
                                              SizedBox(
                                                width: 10,
                                              ),
                                              Text(
                                                '${getSubString(end: 10, str: model.nickname)}',
                                                style: TextStyle(
                                                    fontWeight: FontWeight.bold,
                                                    fontSize: 16,
                                                    color: Color(0xFF7F226B)),
                                              )
                                            ],
                                          ),
                                          InkWell(
                                            onTap: () {
                                              Map arg = {
                                                "coversationType":
                                                    RCIMIWConversationType
                                                        .private,
                                                "targetId": model.userId,
                                                'nickName': model.nickname
                                              };
                                              Navigator.pushNamed(
                                                  context, "/conversation",
                                                  arguments: arg);
                                            },
                                            child: Container(
                                              margin:
                                                  EdgeInsets.only(right: 10),
                                              width: 80,
                                              height: 40,
                                              child: Image.asset(
                                                  'images/icon_home_message.png'),
                                            ),
                                          )
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                              ));
                        }),
                  ))
            ],
          ))
        ],
      ),
    ));
  }

  @override
  void initState() {
    super.initState();
    _getUserInfo();
    loadMore();
    CnEventBus.instance!.addListener(EventKeys.HomeListPageMessage, (arg) {
      Timer(const Duration(milliseconds: 5), () {
        loadMore();
      });
    });
  }

  void _getUserInfo() async {
    CnNetHelper.getUserInfo('',
        (HDHResponseData configData, bool result, String msg) async {
      if (result) {
        UserInfoModel userModel = UserInfoModel.fromJson(configData.data);
        Provider.of<ChangeUserInfoModel>(context, listen: false)
            .setInfo(userModel);
      }
    });
  }

  Widget _cellForRow(context, value) {
    return InkWell(
      onTap: () {},
      child: Container(
        decoration:
            BoxDecoration(border: Border.all(width: 1, color: Colors.white)),
        margin: EdgeInsets.only(left: 5, bottom: 10),
        width: 60,
        height: 80,
        child: Image.asset(
          value,
          fit: BoxFit.cover,
        ),
      ),
    );
  }

//详情弹窗
  void _showInfoDialog(context, model, FunctionTest<int> backBlock) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        bool isFollow = model.isFollow; //是否已经关注

        return StatefulBuilder(builder: (BuildContext, setState) {
          return AlertDialog(
              contentPadding: const EdgeInsets.all(0),
              content: Container(
                decoration: const BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage('images/icon_home_item_bg.png'),
                      fit: BoxFit.fill),
                ),
                height: 368,
                margin: EdgeInsets.all(0),
                child: Column(
                  children: [
                    Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Container(
                            margin: EdgeInsets.only(top: 10),
                            child: Row(
                              children: [
                                SizedBox(
                                  width: 10,
                                ),
                                Container(
                                  width: 30,
                                  height: 30,
                                  clipBehavior: Clip.hardEdge,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(15),
                                  ),
                                  child: Image.network(model.avatar),
                                ),
                                SizedBox(
                                  width: 10,
                                ),
                                Text(
                                  '${getSubString(end: 10, str: model.nickname)}',
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 16,
                                      color: Color(0xFF7F226B)),
                                )
                              ],
                            ),
                          ),
                          InkWell(
                            onTap: () {
                              Navigator.of(context).pop();
                            },
                            child: Container(
                              margin: EdgeInsets.only(right: 10, top: 10),
                              width: 30,
                              height: 30,
                              child: Image.asset('images/ic_close_white.png'),
                            ),
                          )
                        ],
                      ),
                    ),
                    Stack(
                      children: [
                        Container(
                            margin:
                                EdgeInsets.only(top: 20, left: 10, right: 10),
                            height: 248,
                            width: MediaQuery.of(context).size.width - 20 - 32,
                            child: Swiper(
                              itemCount: model.imageMapPaths.length,
                              autoplay: true,
                              itemBuilder: (context, index) {
                                return Image.asset(model.imageMapPaths[index],
                                    fit: BoxFit.fill);
                              },
                              control: SwiperControl(),
                            )),
                        Positioned(
                            bottom: 10,
                            left: 10,
                            child: Container(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Container(
                                        width: 220,
                                        height: 90,
                                        child: ListView.builder(
                                            itemCount:
                                                model.imageMapPaths.length,
                                            scrollDirection:
                                                Axis.horizontal, // 横向滚动
                                            itemBuilder: (context, index) {
                                              return _cellForRow(context,
                                                  model.imageMapPaths[index]);
                                            }),
                                      ),
                                      Container(
                                        margin: EdgeInsets.only(right: 10),
                                        child: InkWell(
                                            onTap: () {
                                              CnAnchorViewModel.getInfo()
                                                  .follow(model.userId,
                                                      model.isFollow,
                                                      (bool value) {
                                                if (value) {
                                                  if (model.isFollow) {
                                                    ToastUtils.show(
                                                        'unfollow success');
                                                  } else {
                                                    ToastUtils.show(
                                                        'follow success');
                                                    CnDatabaseHelper
                                                            .getInstance()
                                                        ?.updateUserInFollow(
                                                            model.userId, true);
                                                  }
                                                  model.isFollow =
                                                      !model.isFollow;
                                                  setState(() {
                                                    isFollow = !isFollow;
                                                  });
                                                } else {
                                                  if (model.isFollow) {
                                                    ToastUtils.show(
                                                        'unfollow failure');
                                                  } else {
                                                    ToastUtils.show(
                                                        'follow failure');
                                                  }
                                                }
                                              });
                                            },
                                            child: !isFollow
                                                ? Image.asset(
                                                    "images/ic_like_false.png",
                                                    height: 30,
                                                    width: 30)
                                                : Image.asset(
                                                    "images/ic_like_true.png",
                                                    height: 30,
                                                    width: 30)),
                                      )
                                    ],
                                  )
                                ],
                              ),
                            )),
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 10),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              SizedBox(
                                width: 10,
                              ),
                              InkWell(
                                onTap: () {
                                  backBlock(0);
                                  Navigator.of(context).pop();
                                },
                                child: Container(
                                  width: 40,
                                  height: 40,
                                  child: Image.asset('images/icon_call.png'),
                                ),
                              ),
                            ],
                          ),
                          InkWell(
                            onTap: () {
                              backBlock(1);
                              Navigator.of(context).pop();
                            },
                            child: Container(
                              margin: EdgeInsets.only(right: 10),
                              width: 80,
                              height: 40,
                              child:
                                  Image.asset('images/icon_home_message.png'),
                            ),
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ));
        });
      },
    );
  }

  Future loadMore() async {
    anchorList.clear();
    List<CnAnchorModel> results = await CnDatabaseHelper.getInstance()
        ?.queryAllAnchorRecords() as List<CnAnchorModel>;
    if (results.isNotEmpty) {
      setState(() {
        anchorList = results;
      });
    } else {
      EasyLoading.show(status: 'loading...');
      List<CnAnchorModel> list =
          await CnAnchorViewModel.getInfo().getAnchorWallList(page: 1);
      EasyLoading.dismiss();
      setState(() {
        _isLoadMore = false;
        if (list.isNotEmpty) {
          for (int i = 0; i < homeImageList.length; i++) {
            CnAnchorModel anchorModel = list[i];
            CnDatabaseHelper.getInstance()?.insertAnchorRecord(
              nickname: anchorModel.nickname,
              userId: anchorModel.userId,
              avatar: anchorModel.avatar,
              country: anchorModel.country,
              imageMapPaths: homeImageList[i].join(','),
              gender: anchorModel.gender,
              callCoins: anchorModel.callCoins,
              age: anchorModel.age,
              followNum: anchorModel.followNum,
              isFollow: false,
            );
            anchorModel.imageMapPaths = homeImageList[i];
            anchorList.add(anchorModel);
          }
        }
      });
    }
  }
}

//字符串截取
String getSubString({required int end, required String str}) {
  if (str.length > end) {
    return "${str.substring(0, end)}...";
  } else {
    return str;
  }
}
